'use strict';

const Transaction = require('../../libs/DB/Transaction');
const operationRecord = require("../sys/operationRecordAction");
const moment = require("moment");
const _ = require("underscore");
const {client} = require("../../libs/Redis/RedisClient");

module.exports = async function (params) {
    let transaction = new Transaction();
    try {
        if(params.deviceIds.length === 0) throw {message:"请选择设备需要绑定的"}
        await transaction.beginTransaction();
        let costPlan = params.costPlan;
        let startTime = moment(params.startTime).format("YYYY-MM-DD HH:mm:ss");
        let deviceList = await transaction.query(`SELECT
                                                          df.device_id AS deviceId,
                                                          df.device_no AS deviceNo,
                                                          df.cost_plan_id AS costPlanId,
                                                          df.device_type AS deviceType,
                                                          cpdm.measure_type AS measureType
                                                      FROM
                                                        device_file df
                                                      INNER JOIN range_file rf ON rf.range_id = df.range_id AND rf.domain_id = ?
                                                      INNER JOIN cost_plan_device_mid cpdm ON cpdm.device_id = df.device_id AND cpdm.measure_type = ?
                                                        WHERE
                                                      df.delete_sign = 1
                                                      AND df.device_id IN (?)`,[params.userDomainId,costPlan.measureType,params.deviceIds])
        let bingingSql = ``;
        if(deviceList.length === 0) throw {message:"没有可以绑定此方案的设备"};
        let deviceObj = _.groupBy(deviceList,"deviceId");
        const multi = client.multi();
        for(const device in deviceObj){
            let bindingInfoList = deviceObj[device];
            bingingSql +=`
            UPDATE cost_plan_device_mid SET cost_plan_id = ${costPlan.costPlanId} WHERE device_id = ${device} AND measure_type = ${bindingInfoList[0].measureType};
            INSERT INTO cost_plan_timeline SET cost_plan_id = ${costPlan.costPlanId},user_id = ${params.userId},device_id = ${device},domain_id = ${params.userDomainId},start_time = "${startTime}";`;
            multi.hmset(`deviceInfo-${bindingInfoList[0].measureType}-${bindingInfoList[0].deviceNo}`,{costPlanId:costPlan.costPlanId});
        }
        await transaction.query(bingingSql);
        multi.exec();
        await transaction.commit();
        await operationRecord(params);
        return {success: true};
    }catch (e){
        await transaction.rollback();
        return {success:false,message:e.message}
    }
};